package com.library.dao;

import com.library.model.ReturnRecord;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ReturnDAO extends BaseDAO {

    // 1. 多条件查询归还记录
    public List<ReturnRecord> findByCondition(String username, String bookTitle, String hasFine) {
        List<ReturnRecord> returns = new ArrayList<>();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        // 动态构建SQL
        StringBuilder sql = new StringBuilder("SELECT * FROM return_record WHERE 1=1");
        List<Object> params = new ArrayList<>();

        if (username != null && !username.isEmpty()) {
            sql.append(" AND username LIKE ?");
            params.add("%" + username + "%");
        }
        if (bookTitle != null && !bookTitle.isEmpty()) {
            sql.append(" AND book_title LIKE ?");
            params.add("%" + bookTitle + "%");
        }
        // 筛选是否有罚款（YES：罚款>0；NO：罚款=0）
        if ("YES".equals(hasFine)) {
            sql.append(" AND fine_amount > 0");
        } else if ("NO".equals(hasFine)) {
            sql.append(" AND fine_amount = 0");
        }

        try {
            conn = getConnection();
            ps = conn.prepareStatement(sql.toString());
            for (int i = 0; i < params.size(); i++) {
                ps.setObject(i + 1, params.get(i));
            }
            rs = ps.executeQuery();

            // 封装结果集
            while (rs.next()) {
                ReturnRecord record = new ReturnRecord();
                record.setId(rs.getInt("id"));
                record.setUsername(rs.getString("username"));
                record.setPhone(rs.getString("phone")); // 允许为null
                record.setBookTitle(rs.getString("book_title"));
                record.setBorrowDate(rs.getDate("borrow_date"));
                record.setExpectReturnDate(rs.getDate("expect_return_date"));
                record.setReturnDate(rs.getDate("return_date"));
                record.setOverdueDays(rs.getInt("overdue_days"));
                record.setFineAmount(rs.getDouble("fine_amount"));
                returns.add(record);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(conn, ps, rs);
        }
        return returns;
    }

    // 2. 新增归还记录（手动录入）
    public void add(ReturnRecord record) {
        String sql = "INSERT INTO return_record " +
                "(username, phone, book_title, borrow_date, expect_return_date, return_date, overdue_days, fine_amount) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
        try {
            executeUpdate(sql,
                    record.getUsername(),
                    record.getPhone(),
                    record.getBookTitle(),
                    record.getBorrowDate(),
                    record.getExpectReturnDate(),
                    record.getReturnDate(),
                    record.getOverdueDays(),
                    record.getFineAmount()
            );
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 3. 更新归还记录
    public void update(ReturnRecord record) {
        String sql = "UPDATE return_record SET " +
                "username=?, phone=?, book_title=?, borrow_date=?, " +
                "expect_return_date=?, return_date=?, overdue_days=?, fine_amount=? " +
                "WHERE id=?";
        try {
            executeUpdate(sql,
                    record.getUsername(),
                    record.getPhone(),
                    record.getBookTitle(),
                    record.getBorrowDate(),
                    record.getExpectReturnDate(),
                    record.getReturnDate(),
                    record.getOverdueDays(),
                    record.getFineAmount(),
                    record.getId()
            );
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 4. 删除归还记录
    public void delete(int id) {
        String sql = "DELETE FROM return_record WHERE id=?";
        try {
            executeUpdate(sql, id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
